<template>
  <div class="card">
    <Title-header title="购买产品送算力"></Title-header>
    <div class="purchase bg-input">
      <div class="purchase__header">
        <span class="text--light">购买产品送算力</span>
      </div>
      <van-field
        v-model="purchaseAmount"
        type="number"
        placeholder="请输入购买算力的数量"
        class="purchase__input"
      >
        <template #left-icon>
          <div style="color: #22825c; font-size: 21px; font-weight: bold">
            $
          </div>
        </template>
        <!-- <template #right-icon>
          <div style="color: #fab81c; font-size: 12px; font-weight: bold">
            {{ infoStore.config.buy_min_power }}USDT起
          </div>
        </template> -->
      </van-field>
      <div class="purchase__power">
        <span class="text--light">获得算力</span>
      </div>
      <van-field
        readonly
        v-model="getPower"
        type="number"
        placeholder="获得的算力值"
        class="purchase__input"
      />

      <p class="text--primary">
        1USDT={{ infoStore.config.usdt_to_power }}算力
      </p>
      <van-button class="btn btn_box" @click="goHandleBuyPower"
        >确定</van-button
      >
    </div>
  </div>
  <MyDialog
    v-model:show="dialogVisible"
    title="提示"
    :content="`是否继续支付 ${purchaseAmount} U购买算力？`"
    @confirm="onConfirm"
  />
</template>

<script setup lang="ts">
import { useInfoStore } from "@/store/infoman";
import { showLoadingToast, showToast, closeToast } from "vant";
import { Recharge, PreRecharge, Apitoken } from "@/api/modules/RechangeW";
import { useConWallet } from "@/hooks/concactWallet.ts";
const props = defineProps({
  parentAd: {
    type: String,
    default: "",
  },
});
// 格式化数字
const purchaseAmount = ref<string>("");
const getPower = computed(() => {
  return (
    Number(purchaseAmount.value) * infoStore?.config.usdt_to_power || "0.00"
  );
});

const infoStore = useInfoStore();
// 获取apitoken
const apiToken = ref<string>("");
const getApitoken = async () => {
  try {
    const res = await Apitoken();
    if (res.code === 0) {
      apiToken.value = res.data.api_token;
    }
  } catch (err) {
    console.log(err);
  }
};
// 充值预下单
const orderSn = ref<string>("");
const getPreRecharge = async () => {
  const data = {
    amount: purchaseAmount.value,
    currency: "USDT",
  };
  const headers = {
    APITOKEN: apiToken.value,
  };
  try {
    const res = await PreRecharge(data, headers);
    if (res.code === 0) {
      orderSn.value = res.data.order_sn;
      getRecharge();
    } else {
      showToast(res.msg);
    }
  } catch (err) {
    console.log(err);
  }
};

// 充值回调
const { BuyPowerTransfer } = useConWallet();
const getRecharge = async () => {
  showLoadingToast({
    message: "加载中...",
    forbidClick: true,
    loadingType: "spinner",
    duration: 0,
  });

  try {
    if (orderSn.value !== "") {
      // 等待 transferErcBTY 完成并获取交易哈希
      const txHash = await BuyPowerTransfer(
        // 0.000001
        purchaseAmount.value,
        //    "0x976AC780Ea219f2A8Ed4180Ec47f081cc514D61e"
        props.parentAd
      );
      if (txHash) {
        const res = await Recharge({
          order_sn: orderSn.value,
          hash: txHash,
        });
        if (res.code === 0) {
          closeToast(); // 点睛之笔，这里关掉后不影响后面的新toast
          showToast(res.msg);
          // showToast({
          //   message: $t("Waitfor"),
          //   duration: "60000",
          // });
          // setTimeout(() => {
          //   purchaseAmount.value = null;
          //   infoStore.getInfo();
          // }, 60000); // 30 seconds delay
          infoStore.getInfo();
        } else {
          showToast(res.msg);
          closeToast(); // 点睛之笔，这里关掉后不影响后面的新toast
        }
      }
    }
  } catch (err) {
    console.log(err);
  }
};

// 购买算力
const dialogVisible = ref(false);
const goHandleBuyPower = () => {
  if (purchaseAmount.value !== "") {
    getApitoken();
    dialogVisible.value = true;
  }
};
// 确认购买算力
const onConfirm = async () => {
  getPreRecharge();
};
</script>

<style scoped lang="less">
@import "../styles/common.less";
.purchase {
  padding: 20px;

  &__header,
  &__power {
    .flex-between();
    .text--light {
      font-size: 16px;
      color: #22825c;
    }
  }

  .text--primary {
    text-align: right;
    font-size: 12px;
    color: #22825c;
  }

  &__input {
    background-color: #dbf7ee;
    border-radius: 10px;
    margin: 15px 0px;
  }

  .btn_box {
    width: 307px;
    height: 47px;
    background: linear-gradient(158deg, #31dfb0 0%, #0fc68a 100%);
    border-radius: 52px;
    color: #fff;
    box-shadow: 0px 0px 1px 2px rgba(2, 232, 155, 0.5);
  }
}
</style>
